import { defineStore } from 'pinia'
import request from '@/extensions/axios'
const env = import.meta.env
export const useConfigStore = defineStore('config', {
  state: () => {
    return {
      config:{},
      loading:false,
      error:null,
      loaded:false,
    }
  },
  getters: {
    clientId: (state) => {
      return state?.config?.client_id;
    },
    logo: (state) => {
      const logoUrl = state?.config?.logo;
      const app_url = state?.config?.app_url || env.VITE_API_BASE_URL || '';
      if(!logoUrl){
        return '';
      }
      return logoUrl.startsWith('http')? logoUrl : app_url+logoUrl;
    }
  },
  actions: {
      async fetchConfig() {
        //已经加载过不用再加载
        if(this.loaded){
          return
        }
        //数据请求中,锁定重复请求
        if(this.loading){
          return;
        }
        //数据请求完成,处理数据
        const complete = ()=>{
          if(this.config?.page_gray==1){
            document.querySelector('html').style.filter='grayscale(100%)';
          }
          this.loaded = true;
          if(!this.config?.app_url){
            this.config.app_url = env.VITE_API_BASE_URL || '';
          }
        }
        //script标签方式加载配置,直接处理数据
        if(typeof window.AppConfig === 'object'){
          this.config = window.AppConfig;
          complete();
          return;
        }
      
        let response = null;
        const configScript = document.getElementById('app-config');
        if(!configScript){ //如果没有script标签,则从后台获取配置
          this.loading = true;
          try{
            response = await request.get('/open/config');
          }catch(error){
            console.error('后台接口地址配置错误:', error.message);
          }
        }
        this.loading = false; //数据请求完成,解锁重复请求
        if(response &&
          response.status === 200 && 
          response.data && 
          response.data.client_id
        ){
          this.config = response.data;
          complete();
        }
      },
  }
})